﻿using System;
using System.Collections.Generic;
using Core.Interfaces;

namespace Core.Base.Module
{
    /// <summary>
    /// 所有Module的基类
    /// </summary>
    public abstract class BaseModule : CancelTokenExtension
    {
        private Dictionary<Type, BaseMgr> mgrs = new Dictionary<Type, BaseMgr>();

        public override void OnInit()
        {
            base.OnInit();
            InitMgr();
        }

        /// <summary>
        /// 注册该模块下的Mgr
        /// </summary>
        protected abstract void InitMgr();

        /// <summary>
        /// 注册Mgr并初始化
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        public T RegMgr<T>() where T : BaseMgr
        {
            T mgr = default;
            Type type = typeof(T);
            if (!mgrs.ContainsKey(type))
            {
                mgr = Activator.CreateInstance(type, true) as T;
                mgrs.Add(type, mgr);
                mgr.OnInit();
            }

            return mgr;
        }


        /// <summary>
        /// 注销
        /// </summary>
        /// <typeparam name="T"></typeparam>
        public virtual void UnRegMgr<T>() where T : BaseMgr
        {
            Type type = typeof(T);
            if (mgrs.TryGetValue(type, out BaseMgr mgr))
            {
                mgr.OnDestroy();
                mgrs.Remove(type);
            }
        }


        /// <summary>
        /// 检索Mgr
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        public T RetrieveMgr<T>() where T : BaseMgr
        {
            T ret = default;
            Type type = typeof(T);
            if (mgrs.TryGetValue(type, out BaseMgr mgr))
            {
                ret = mgr as T;
            }

            return ret;
        }

        public override void OnDestroy()
        {
            foreach (var item in mgrs.Values)
            {
                item.OnDestroy();
            }

            mgrs.Clear();
            base.OnDestroy();
        }
    }
}